/*
 * Directory.cpp
 *
 *  Created on: 26/06/2014
 *      Author: Vitor
 */

#include "Directory.h"

Directory::Directory(std::string name, Directory* parent) :
		FileSystemElement(name), parent(parent) {
}

Directory::~Directory() {
	for (auto element : children) {
		delete (element);
	}
}

FileSystemElement* Directory::get_element_from_path(std::string path) {
	if (path == name) {
		return this;
	}
	for (auto& element : children) {
		if (path.find(element->get_name()) != std::string::npos) {
			if (path == element->get_name()) {
				return element;
			}
			return ((Directory*) element)->get_element_from_path(path);
		}
	}
	return nullptr;
}

std::string Directory::html_children_encoding() {
	std::string html;

	for (auto& child : children) {
		html += child->html_encoding();
	}
	return html;
}

std::string Directory::html_encoding() {
	std::string path = name.substr(0, name.length() - 1);

	auto found = path.find_last_of("/");
	path = path.substr(found + 1);
	path += "/";

	std::string html(
			"\t\t\t<tr>\n\t\t\t\t<td>\n\t\t\t\t\t<a href=\"" + path
					+ "\"><font color=\"white\" size=\"5\">" + path
					+ "</font></a>\n\t\t\t\t</td>\n\t\t\t\t<td>\n\t\t\t\t\t<form action=\"\" method=\"post\" name=\""
					+ path
					+ "\">\n\t\t\t\t\t\t<input type=\"hidden\" name=\"form\" value=\""
					+ path
					+ "\">\n\t\t\t\t\t\t<select name=\"acao\">\n\t\t\t\t\t\t\t<option value=\"Renomear\">Renomear</option>\n\t\t\t\t\t\t\t<option value=\"Deletar\">Deletar</option>\n\t\t\t\t\t\t</select>\n\t\t\t\t\t\t<input type=\"text\" name=\"newName\">\n\t\t\t\t\t\t<input type=\"submit\" value=\"OK\">\n\t\t\t\t\t</form>\n\t\t\t\t</td>\n\t\t\t</tr>\n");
	return html;
}

void Directory::rename(std::string old_full_path, std::string new_full_path) {
	name.replace(name.find(old_full_path), old_full_path.length(),
			new_full_path);
	for (auto& element : children) {
		element->rename(old_full_path, new_full_path);
	}
}

ByteQueue Directory::serialize() {
	ByteQueue bytes;
	bytes.push<char>(DIRECTORY);
	bytes.push<std::string>(name);
	for (auto& child : children) {
		bytes = bytes.append(child->serialize());
	}
	bytes.push<char>(END_OF_CHILDREN);
	return bytes;
}
